<script setup lang="ts">
import {
  createEnterpriseAPI,
  getIndustryListAPI,
  uploadAPI,
} from "@/apis/enterprise";
import router from "@/router";
import type { Industry } from "@/types/enterprise";
import {
  ElMessage,
  type FormInstance,
  type FormRules,
  type UploadInstance,
  type UploadRawFile,
  type UploadRequestOptions,
} from "element-plus";
import { onMounted, reactive, ref } from "vue";

const addForm = reactive({
  name: "", // 企业名称
  legalPerson: "", // 法人
  registeredAddress: "", // 注册地址
  industryCode: "", // 所在行业
  contact: "", // 企业联系人
  contactNumber: "", // 联系人电话
  businessLicenseUrl: "", // 营业执照url
  businessLicenseId: "", // 营业执照id
});

const industryList = ref<Industry[]>([]); // 可选行业列表
const getIndustryList = async () => {
  const res = await getIndustryListAPI();
  industryList.value = res.data;
};

// const fileList = ref<UploadUserFile[]>([]); // 营业执照列表

// 上传文件
const uploadFile = async (options: UploadRequestOptions) => {
  console.log(options);
  // 准备 fromData 对象
  const formData = new FormData();
  // 文件
  formData.append("file", options.file);
  // 上传类型
  formData.append("type", "businessLicense");
  const res = await uploadAPI(formData);
  // console.log("长传文件成功", res);
  // 保存营业执照 id 和 url
  addForm.businessLicenseId = res.data.id;
  addForm.businessLicenseUrl = res.data.url;
  // 主动触发校验（校验通过）
  addFormRef.value?.validateField("businessLicenseId");
};

// 上传文件之前的钩子，参数为上传的文件， 若返回false或者返回 Promise 且被 reject，则停止上传。
const beforeUpload = (rawFile: UploadRawFile) => {
  // 大小限制：5M
  const size5M = 5 * 1024 * 1024;
  // 格式限制：.png .jpg .jpeg
  const AcceptType = ["image/png", "image/jpeg", "image/jpg"];
  if (rawFile.size > size5M) {
    ElMessage.error("文件大小不能超过5M");
    return false;
  } else if (AcceptType.includes(rawFile.type) === false) {
    ElMessage.error("仅支持扩展名：.png .jpg .jpeg");
    return false;
  }
};

// 删除了文件
const onFileRemove = () => {
  // 清空营业执照信息
  addForm.businessLicenseId = "";
  addForm.businessLicenseUrl = "";
};

// 表单校验
const addFormRules = reactive<FormRules<typeof addForm>>({
  name: [{ required: true, message: "请输入企业名称", trigger: "blur" }],
  legalPerson: [{ required: true, message: "请输入法人", trigger: "blur" }],
  registeredAddress: [
    { required: true, message: "请输入注册地址", trigger: "blur" },
  ],
  industryCode: [
    { required: true, message: "请选择所属行业", trigger: "change" },
  ],
  contact: [{ required: true, message: "请输入联系人", trigger: "blur" }],
  contactNumber: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    { pattern: /^1\d{10}$/, message: "请输入正确的手机号" },
  ],
  businessLicenseId: [
    { required: true, message: "请上传营业执照", trigger: "change" },
  ],
  businessLicenseUrl: [
    { required: true, message: "请上传营业执照", trigger: "change" },
  ],
});

// 用于统一表单校验
const addFormRef = ref<FormInstance>();

// 加载弹窗（防抖节流）
const onSubmitLoading = ref(false);

// 提交表单
const onSubmit = async () => {
  try {
    // 统一表单校验
    await addFormRef.value?.validate();
    onSubmitLoading.value = true;
    // 提交表单
    await createEnterpriseAPI(addForm);
    ElMessage({ message: "添加成功" });
    // 返回删一页
    router.back();
  } catch (error) {
    ElMessage.error("请按要求完善企业信息");
  } finally {
    onSubmitLoading.value = false;
  }
};

const uploadRef = ref<UploadInstance>();
// 重置表单
const resetForm = () => {
  // 清空 url
  addForm.businessLicenseUrl = "";
  // 重置常规表单
  addFormRef.value?.resetFields();
  // 重置清空已上传的文件列表
  uploadRef.value?.clearFiles();
};

onMounted(() => {
  getIndustryList();
});
</script>

<template>
  <div class="add-enterprise">
    <header class="add-header">
      <el-page-header content="添加企业" @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form
            ref="addFormRef"
            :model="addForm"
            :rules="addFormRules"
            label-width="100px"
          >
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" clearable />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" clearable />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" clearable />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode" clearable>
                <el-option
                  v-for="item in industryList"
                  :key="item.industryCode"
                  :value="item.industryCode"
                  :label="item.industryName"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input
                v-model="addForm.contactNumber"
                maxlength="11"
                clearable
              />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseId">
              <el-upload
                ref="uploadRef"
                name="file"
                drag
                :limit="1"
                :http-request="uploadFile"
                accept=".png, .jpg, .jpeg"
                :before-upload="beforeUpload"
                :on-remove="onFileRemove"
              >
                <template #trigger>
                  <el-button size="small" type="primary">点击上传</el-button>
                </template>
                <template #tip>
                  <div class="el-upload__tip">
                    支持扩展名：.png .jpg .jpeg, 文件大小不得超过5M
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-form>
          {{ addForm }}
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="resetForm">重置</el-button>
        <el-button :loading="onSubmitLoading" type="primary" @click="onSubmit"
          >确定</el-button
        >
      </div>
    </footer>
  </div>
</template>

<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
